<template>
  <div class="policy-documents-container">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span>政策文件管理</span>
          <el-button type="primary" @click="showAddDocumentDialog">添加政策文件</el-button>
        </div>
      </template>
      
      <!-- 搜索和筛选 -->
      <div class="search-filter-section">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="文件标题">
            <el-input 
              v-model="searchForm.document_title" 
              placeholder="请输入文件标题"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="文件类型">
            <el-select 
              v-model="searchForm.document_type" 
              placeholder="请选择文件类型"
              clearable
            >
              <el-option label="指南规范" value="指南规范"></el-option>
              <el-option label="政策法规" value="政策法规"></el-option>
              <el-option label="专家共识" value="专家共识"></el-option>
              <el-option label="标准文件" value="标准文件"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布时间范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 数据表格 -->
      <el-table 
        v-loading="loading" 
        :data="paginatedDocuments" 
        style="width: 100%"
        border
      >
        <el-table-column prop="document_id" label="文件ID" width="100" />
        <el-table-column prop="document_title" label="文件标题" min-width="250">
          <template #default="{ row }">
            <span class="document-title" @click="viewDocumentDetail(row.document_id)">{{ row.document_title }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="document_type" label="文件类型" width="120" />
        <el-table-column prop="department" label="发布部门" width="150" />
        <el-table-column prop="publish_date" label="发布时间" width="150" />
        <el-table-column prop="version" label="版本" width="80" />
        <el-table-column prop="download_count" label="下载次数" width="100">
          <template #default="{ row }">
            <el-tag size="small" effect="plain">{{ row.download_count || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="row.status === '发布' ? 'success' : 'draft'" 
              effect="plain"
            >
              {{ row.status === '发布' ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="downloadDocument(row)">下载</el-button>
            <el-button type="primary" size="small" @click="editDocument(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteDocument(row.document_id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredDocuments.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑政策文件对话框 -->
    <el-dialog
      v-model="documentDialogVisible"
      :title="dialogType === 'add' ? '添加政策文件' : '编辑政策文件'"
      width="700px"
    >
      <el-form 
        :model="documentForm" 
        ref="documentFormRef" 
        label-width="120px"
        :rules="formRules"
      >
        <el-form-item label="文件标题" prop="document_title">
          <el-input 
            v-model="documentForm.document_title" 
            placeholder="请输入文件标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="文件类型" prop="document_type">
          <el-select v-model="documentForm.document_type" placeholder="请选择文件类型">
            <el-option label="指南规范" value="指南规范"></el-option>
            <el-option label="政策法规" value="政策法规"></el-option>
            <el-option label="专家共识" value="专家共识"></el-option>
            <el-option label="标准文件" value="标准文件"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布部门" prop="department">
          <el-input 
            v-model="documentForm.department" 
            placeholder="请输入发布部门"
          ></el-input>
        </el-form-item>
        <el-form-item label="发布时间" prop="publish_date">
          <el-date-picker
            v-model="documentForm.publish_date"
            type="date"
            placeholder="选择发布时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="版本" prop="version">
          <el-input 
            v-model="documentForm.version" 
            placeholder="请输入版本号（如 v1.0）"
          ></el-input>
        </el-form-item>
        <el-form-item label="文件链接" prop="file_link" v-if="dialogType === 'edit' && documentForm.file_link">
          <el-input 
            v-model="documentForm.file_link" 
            placeholder="请输入文件下载链接"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="上传文件" prop="file_path">
          <el-upload
            class="upload-demo"
            drag
            action="#"
            :on-change="handleFileChange"
            :auto-upload="false"
            :limit="1"
            accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              <em>点击或拖拽文件到此处上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              支持 .pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx 格式文件
            </div>
          </el-upload>
          <div v-if="documentForm.file_name" class="file-info">
            <el-tag size="small" type="success">{{ documentForm.file_name }}</el-tag>
          </div>
        </el-form-item>
        <el-form-item label="文件摘要" prop="document_summary">
          <el-input 
            v-model="documentForm.document_summary" 
            placeholder="请输入文件摘要"
            type="textarea"
            rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item label="关键词" prop="keywords">
          <el-input 
            v-model="documentForm.keywords" 
            placeholder="请输入关键词，用逗号分隔"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="documentForm.status">
            <el-radio value="draft">草稿</el-radio>
            <el-radio value="发布">发布</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input 
            v-model="documentForm.notes" 
            placeholder="请输入备注信息"
            type="textarea"
            rows="2"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="documentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitDocumentForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { policyAPI } from '../api'

// 状态数据
const loading = ref(false)
const documents = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const searchForm = ref({
  document_title: '',
  document_type: ''
})
const dateRange = ref([])

// 对话框相关
const documentDialogVisible = ref(false)
const dialogType = ref('add')
const documentFormRef = ref()
const documentForm = ref({
  document_id: '',
  document_title: '',
  document_type: '',
  department: '',
  publish_date: '',
  version: 'v1.0',
  file_path: '',
  file_name: '',
  file_link: '',
  document_summary: '',
  keywords: '',
  download_count: 0,
  status: 'draft',
  notes: ''
})

// 表单验证规则
const formRules = {
  document_title: [
    { required: true, message: '请输入文件标题', trigger: 'blur' },
    { min: 2, max: 200, message: '文件标题长度应在 2 到 200 个字符之间', trigger: 'blur' }
  ],
  document_type: [
    { required: true, message: '请选择文件类型', trigger: 'change' }
  ],
  department: [
    { required: true, message: '请输入发布部门', trigger: 'blur' }
  ],
  publish_date: [
    { required: true, message: '请选择发布时间', trigger: 'change' }
  ],
  document_summary: [
    { required: true, message: '请输入文件摘要', trigger: 'blur' }
  ]
}

// 根据搜索条件过滤政策文件
const filteredDocuments = computed(() => {
  let result = documents.value
  
  // 根据文件标题过滤
  if (searchForm.value.document_title) {
    const title = searchForm.value.document_title
    result = result.filter(doc => doc.document_title.includes(title))
  }
  
  // 根据文件类型过滤
  if (searchForm.value.document_type) {
    result = result.filter(doc => doc.document_type === searchForm.value.document_type)
  }
  
  // 根据日期范围过滤
  if (dateRange.value && dateRange.value.length === 2) {
    const startDate = new Date(dateRange.value[0])
    const endDate = new Date(dateRange.value[1])
    endDate.setHours(23, 59, 59, 999)
    
    result = result.filter(doc => {
      const publishDate = new Date(doc.publish_date)
      return publishDate >= startDate && publishDate <= endDate
    })
  }
  
  return result
})

// 分页政策文件
const paginatedDocuments = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredDocuments.value.slice(start, end)
})

// 获取数据
const getData = async () => {
  loading.value = true
  try {
    // 获取政策文件列表
    const data = await policyAPI.getDocuments()
    
    // 字段映射：将中文字段名转换为组件需要的英文字段名
    documents.value = data.map(item => ({
      document_id: item['文件ID'] || item.id,
      document_title: item['文件标题'],
      document_type: item['文件类型'] || '指南规范',
      department: item['发布部门'] || '卫生部',
      publish_date: item['发布时间'],
      version: item['版本'] || 'v1.0',
      download_count: item['浏览量'] || 0,
      status: '发布',
      file_link: '',
      document_summary: item['文件内容'] || ''
    }))
  } catch (error) {
    ElMessage.error('获取数据失败')
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    document_title: '',
    document_type: ''
  }
  dateRange.value = []
  currentPage.value = 1
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (current) => {
  currentPage.value = current
}

// 文件上传处理
const handleFileChange = (file, fileList) => {
  if (fileList.length > 0) {
    // 由于是模拟环境，这里仅保存文件名
    documentForm.value.file_name = file.name
    documentForm.value.file_path = `/uploads/${file.name}`
    // 在实际项目中，这里应该进行文件上传
  }
}

// 显示添加政策文件对话框
const showAddDocumentDialog = () => {
  dialogType.value = 'add'
  documentForm.value = {
    document_id: '',
    document_title: '',
    document_type: '',
    department: '',
    publish_date: new Date().toISOString().split('T')[0],
    version: 'v1.0',
    file_path: '',
    file_name: '',
    file_link: '',
    document_summary: '',
    keywords: '',
    download_count: 0,
    status: 'draft',
    notes: ''
  }
  documentDialogVisible.value = true
}

// 编辑政策文件
const editDocument = (row) => {
  dialogType.value = 'edit'
  documentForm.value = { ...row }
  // 确保发布时间是日期格式
  if (row.publish_date && typeof row.publish_date === 'string') {
    documentForm.value.publish_date = row.publish_date.split('T')[0]
  }
  documentDialogVisible.value = true
}

// 提交表单
const submitDocumentForm = async () => {
  try {
    await documentFormRef.value.validate()
    
    // 处理表单数据
    const formData = { ...documentForm.value }
    
    // 生成文件链接（模拟）
    if (!formData.file_link && formData.file_path) {
      formData.file_link = `https://example.com/files${formData.file_path}`
    }
    
    if (dialogType.value === 'add') {
      // 生成文件ID
      const newDocument = {
        ...formData,
        document_id: Date.now(), // 简单生成ID
        creation_time: new Date().toISOString(),
        download_count: 0
      }
      
      await policyAPI.addDocument(newDocument)
      ElMessage.success('政策文件添加成功')
    } else {
      const updatedDocument = {
        ...formData,
        update_time: new Date().toISOString()
      }
      await policyAPI.updateDocument(updatedDocument)
      ElMessage.success('政策文件更新成功')
    }
    
    documentDialogVisible.value = false
    getData() // 重新获取数据
  } catch (error) {
    if (error !== false) { // 非表单验证错误
      ElMessage.error('操作失败，请重试')
      console.error('操作失败:', error)
    }
  }
}

// 删除政策文件
const deleteDocument = async (documentId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该政策文件吗？此操作不可撤销！',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await policyAPI.deleteDocument(documentId)
    ElMessage.success('政策文件已删除')
    getData() // 重新获取数据
  } catch (error) {
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error('删除失败')
      console.error('删除失败:', error)
    }
  }
}

// 查看政策文件详情
const viewDocumentDetail = (documentId) => {
  // 这里可以实现跳转到政策文件详情页面
  ElMessage.success('查看政策文件详情功能待实现')
}

// 下载政策文件
const downloadDocument = async (document) => {
  try {
    // 模拟下载，并更新下载次数
    if (document.file_link) {
      // 在实际项目中，这里应该打开文件链接或执行下载
      console.log('下载文件:', document.file_link)
      
      // 更新下载次数
      const updatedDocument = {
        ...document,
        download_count: (document.download_count || 0) + 1
      }
      await policyAPI.updateDocument(updatedDocument) 
      
      ElMessage.success('文件下载成功')
      getData() // 重新获取数据以更新下载次数
    } else {
      ElMessage.warning('文件链接不存在，无法下载')
    }
  } catch (error) {
    ElMessage.error('下载失败')
    console.error('下载失败:', error)
  }
}

// 组件挂载时获取数据
onMounted(() => {
  getData()
})
</script>

<style scoped>
.policy-documents-container {
  padding: 20px;
  background-color: #FFFFFF;
  min-height: 100vh;
  border: 1px solid #e0e0e0;
}

.page-card {
  margin-bottom: 20px;
  background-color: #FFFFFF;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  box-shadow: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #000000;
}

/* 确保标题文字为黑色 */
.card-header span {
  color: #000000 !important;
}

.search-filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #FFFFFF;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
  box-shadow: none;
}

.search-form {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.document-title {
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}

.document-title:hover {
  color: #66b1ff;
}

.file-info {
  margin-top: 10px;
}

/* 适配Element Plus深色主题下的组件 */
:deep(.el-input__wrapper),
:deep(.el-select__wrapper),
:deep(.el-date-editor .el-input__wrapper) {
  background-color: #FFFFFF !important;
  border-color: #dcdfe6 !important;
  color: #000000;
}

:deep(.el-input__placeholder),
:deep(.el-select__placeholder) {
  color: #c0c4cc !important;
}

:deep(.el-input__inner),
:deep(.el-select__input) {
  color: #000000 !important;
}

:deep(.el-input__wrapper:hover),
:deep(.el-select__wrapper:hover),
:deep(.el-date-editor .el-input__wrapper:hover) {
  border-color: #666 !important;
}

:deep(.el-input__wrapper.is-focus),
:deep(.el-select__wrapper.is-focus),
:deep(.el-date-editor .el-input__wrapper.is-focus) {
  border-color: #409eff !important;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2) !important;
}

/* 表格样式 */
:deep(.el-table) {
  background-color: #FFFFFF;
  color: #000000;
}

:deep(.el-table__header-wrapper th) {
  background-color: #f5f7fa;
  color: #000000;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table__row) {
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 按钮样式 */
:deep(.el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-button--primary:hover) {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

:deep(.el-button--default) {
  background-color: #ffffff;
  border-color: #dcdfe6;
  color: #606266;
}

:deep(.el-button--default:hover) {
  background-color: #f5f7fa;
  border-color: #c0c4cc;
  color: #409eff;
}

/* 对话框样式 */
:deep(.el-dialog__wrapper .el-dialog) {
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
}

:deep(.el-dialog__wrapper .el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  background-color: #ffffff;
}

:deep(.el-dialog__wrapper .el-dialog__title) {
  color: #000000;
}

:deep(.el-dialog__wrapper .el-form-item__label) {
  color: #000000;
}

:deep(.el-dialog__body) {
  background-color: #ffffff;
}

:deep(.el-dialog__footer) {
  background-color: #ffffff;
  border-top: 1px solid #ebeef5;
}

/* 上传组件样式 */
:deep(.el-upload-dragger) {
  background-color: #fafafa;
  border: 2px dashed #dcdfe6;
  color: #000000;
}

:deep(.el-upload-dragger:hover) {
  border-color: #409eff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form .el-form-item {
    margin-bottom: 15px;
  }
}
</style>